package com.ssrs.framework.extend;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.ssrs.framework.extend.annotation.ExtendItem;
import com.ssrs.framework.extend.plugin.PluginConfig;
import com.ssrs.framework.extend.plugin.PluginException;
import org.w3c.dom.Element;


/**
 * 扩展项类，对应一个扩展项
 *
 * @author ssrs
 */
public class ExtendItemConfig {
    private boolean enable;
    private PluginConfig pluginConfig;
    private String id;
    private String description;
    private String extendServiceId;
    private String className;
    private IExtendItem instance = null;

    public void init(PluginConfig pc, Class<?> clazz) throws PluginException {
        ExtendItem extendItem = clazz.getAnnotation(ExtendItem.class);
        pluginConfig = pc;
        id = clazz.getName();
        description = extendItem.description();
        extendServiceId = extendItem.extendService().getName();
        className = clazz.getName();
        if (StrUtil.isEmpty(id)) {
            throw new PluginException("extendItem's id is empty!");
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getExtendServiceId() {
        return extendServiceId;
    }

    public void setExtendServiceId(String extendServiceId) {
        this.extendServiceId = extendServiceId;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public boolean isEnable() {
        return enable;
    }

    public PluginConfig getPluginConfig() {
        return pluginConfig;
    }


    public String getDescription() {
        return description;
    }


    public String getClassName() {
        return className;
    }


    public void setDescription(String description) {
        this.description = description;
    }


    public void setClassName(String className) {
        this.className = className;
    }

    public IExtendItem getInstance() {
        try {
            if (instance == null) {
                Class<?> clazz = Class.forName(className);
                try {
                    instance = (IExtendItem) clazz.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("ExtendItem " + className + " must implements IExtendItem");
                }
            }
            return instance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
